package com.briup.srms.sms.web.controller;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.briup.srms.sms.bean.StudentEmployment;
import com.briup.srms.sms.bean.extend.StudentEmploymentExtend;
import com.briup.srms.sms.service.IStudentEmploymentService;
import com.jacky.base.utils.ExcelUtils;
import com.jacky.base.utils.Message;
import com.jacky.base.utils.MessageUtil;
import com.jacky.base.utils.PageVM;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: 杰普基础管理系统
 * @description: 学生控制器类
 * @author: charles
 * @create: 2020-12-27 17:22
 **/
@Api(description = "学生就业相关接口")
@Validated
@RestController
@RequestMapping("/studentEmployment")
public class StudentEmploymentController {

	@Autowired
	private IStudentEmploymentService studentEmploymentService;

	@ApiOperation(value = "分页多条件获取学生就业信息")
	@GetMapping("pageQuery")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
			@ApiImplicitParam(name = "realname", value = "姓名", paramType = "query"),
			@ApiImplicitParam(name = "clazzId", value = "杰普班级编号", paramType = "query"),
			@ApiImplicitParam(name = "status", value = "状态", paramType = "query"),
			@ApiImplicitParam(name = "channelIds", value = "渠道", paramType = "query"),
			@ApiImplicitParam(name = "stuTypes", value = "学生类型", paramType = "query"),
			@ApiImplicitParam(name = "year", value = "毕业年份", paramType = "query"),

			@ApiImplicitParam(name = "employmentTeacher", value = "就业部老师姓名", paramType = "query"),
			@ApiImplicitParam(name = "employmentClazzName", value = "就业管理班号", paramType = "query"),

	})
	public Message pageQuery(@NotNull int page, int pageSize,String realname,Long clazzId,String status,Long[] channelIds,String[] stuTypes,String year,
		String employmentTeacher,String employmentClazzName
	) {
        System.out.println("【EmployeePageQuery】");
		PageVM<StudentEmploymentExtend> pageVM = studentEmploymentService.pageQuery(page, pageSize,realname,clazzId,status,channelIds,stuTypes,year,
				employmentTeacher,employmentClazzName);
		return MessageUtil.success(pageVM);
	}

	@ApiOperation(value = "更新学生就业信息")
	@PostMapping("update")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "idCard", value = "身份证号", required = true, paramType = "query"),
	})
	public Message pageQuery(StudentEmployment employment) {
        System.out.println("【update学生就业信息】");
		studentEmploymentService.update(employment);
		return MessageUtil.success("更新成功！");
	}

	@ApiOperation(value = "下载批量导入模板", produces = "application/octet-stream")
	@GetMapping("downloadTemplate")
	public void downloadTemplate(HttpServletResponse response) throws Exception {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = this.getClass().getResourceAsStream("/template/student_employment_template.xlsx");
			outputStream = response.getOutputStream();
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("Content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("批量导入学生就业信息模板.xlsx", "utf-8"));
			IOUtils.copy(inputStream, outputStream);
			response.flushBuffer();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(outputStream !=null) {
				outputStream.close();
			}
		}
	}

	@ApiOperation(value = "批量导入学生就业信息", notes = "")
	@PostMapping("upload")
	public Message upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws Exception {
		File toFile = null;
		if (file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		// 解析数据
		List<List<Object>> list = ExcelUtils.readExcel(toFile);
		List<StudentEmployment> employments = new ArrayList<>();
		for (List<Object> props : list) {
			StudentEmployment employment = new StudentEmployment();
			// 设置基本信息
			for (int i=0;i<props.size();i++) {
				Object prop = props.get(i);
				switch (i) {
					// 身份证号
					case 0:employment.setIdCard(prop+"");	break;
					// 就业序号
					case 1:employment.setSerialNumber(prop+"");	break;
					// 就业老师
					case 2:employment.setEmploymentTeacher(prop+"");break;
					// 考研是否录取
					case 3:employment.setIsGraduate(prop+"");break;
					//报考院校及专业
					case 4:employment.setGraduateCollege(prop+"");break;
					// 灵活信息1
					case 5:employment.setFlexibleInformation1(prop+"");break;
					// 灵活信息2
					case 6:employment.setFlexibleInformation2(prop+"");break;
					// 就业部离校审批
					case 7:employment.setLeaveCheck(prop+"");break;
					// 模面等级
					case 8:employment.setInterviewLevel(prop+"");break;
					// 面试评价
					case 9:employment.setInterviewComment(prop+"");break;
					// 首轮就业意向调研
					case 10:employment.setIntention(prop+"");break;
					// 就业推荐及回访记录
					case 11:employment.setRecommendRecord(prop+"");break;
					// 三方回访记录
					case 12:employment.setTripartiteAgreement(prop+"");break;
					// 学校系统匹配数据查找
					case 13:employment.setSchoolDataSearch(prop+"");break;
					// 三方签约情况
					case 14:employment.setTripartiteAgreementStatus(prop+"");break;
					// 就业状态
					case 15:employment.setStatus(prop+"");break;
					// 目前所在地
					case 16:employment.setCurrentLocation(prop+"");break;
					// 入职时间
					case 17:employment.setEntryTime(prop+"");break;
					// 首份工作公司
					case 18:employment.setCompanyName(prop+"");break;
					// 公司性质
					case 19:employment.setCompanyNature(prop+"");break;
					//实习月薪
					case 20:employment.setSalaryMonth(prop+"");break;
					// 转正月薪
					case 21:employment.setSalaryInternshipMonth(prop+"");break;
					// 转正年薪
					case 22:employment.setSalaryYear(prop+"");break;
					// 具体岗位
					case 23:employment.setPost(prop+"");break;
					// 离职公司
					case 24:employment.setDimissionCompany(prop+"");break;
					// 离职时间
					case 25:employment.setDimissionTime(prop+"");break;
					// 离职理由
					case 26:employment.setDimissionReason(prop+"");break;
					// 学员情况标注
					case 27:employment.setComment(prop+"");break;
					// 就业管理班号
					case 28:employment.setEmploymentClazzName(prop+"");break;
					// 系统班级号（杰普系统查询使用）
					case 29:employment.setSrmsClazzName(prop+"");break;
					// 姓名
					case 32:employment.setName(prop+"");	break;
				default:
					break;
				}
			}
			employments.add(employment);
		}
		// 调用业务逻辑层代码完成批量保存操作
		List<StudentEmployment> errorList = studentEmploymentService.batchUpdate(employments);
		// 上传失败的就业信息维护到上下文中
		if(errorList.size()>0){
			req.getServletContext().setAttribute("errorList",errorList);
		}
		return MessageUtil.success(errorList);
	}

	@ApiOperation(value = "导出导入失败的就业信息到到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "application/octet-stream")
	@GetMapping("downloadErrorList")
	public void downloadErrorList(HttpServletResponse response,HttpServletRequest request) throws Exception {
		ServletContext context =  request.getServletContext();
		List<StudentEmployment> errorList =(List<StudentEmployment>)context.getAttribute("errorList");
		// 2. 将excel导出
		// 2.1 excel头部数据
		String[] headList = new String[] {
				"身份证号","就业档案排序号","就业部老师","考研是否录取","报考院校及专业","灵活信息1","灵活信息2","就业部离校审批情况","模面成绩","面试评价","首轮就业意向调研","就业推荐回访记录","三方协议回访情况","学校系统匹配数据查找","三方协议签约情况","就业状态",
				"目前所在地","入职时间","首份工作公司","公司性质","转正年薪","实习月薪","转正月薪","工作岗位","离职公司","离职时间","离职理由","学员情况标注",
				"就业管理班号","系统班级号","姓名"
		};
		// 2.2 属性
		String[] fieldList = new String[] {
				"id_card","serial_number","employment_teacher","is_graduate","graduate_college","flexible_information_1","flexible_information_2","leave_check","interview_level","interview_comment","intention","recommend_record","tripartite_agreement","school_data_search","tripartite_agreement_status","status",
				"current_location","entry_time","company_name","company_nature","salary_year","salary_internship_month","salary_month","post","dimission_company","dimission_time","dimission_reason","comment",
				"employment_clazz_name", "srms_clazz_name",  "realname"
		};

		// 2.3 数据列，需要转化
		List<Map<String, Object>> dataList = new ArrayList<>();
		for (StudentEmployment u : errorList) {
			Map<String, Object> map = new HashMap<>();
			// 日期处理函数
			SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
			if(u != null) {
				map.put("id_card",u.getIdCard());
				map.put("employment_teacher", u.getEmploymentTeacher());
				map.put("is_graduate", u.getIsGraduate());
				map.put("graduate_college", u.getGraduateCollege());
				map.put("interview_level", u.getInterviewLevel());
				map.put("interview_comment", u.getInterviewComment());
				map.put("intention", u.getIntention());
				map.put("leave_check", u.getLeaveCheck());
				map.put("recommend_record", u.getRecommendRecord());
				map.put("tripartite_agreement", u.getTripartiteAgreement());
				map.put("tripartite_agreement_status", u.getTripartiteAgreementStatus());
				map.put("status", u.getStatus());
				map.put("current_location",u.getCurrentLocation());
				map.put("entry_time", u.getEntryTime());
				map.put("company_name", u.getCompanyName());
				map.put("company_nature", u.getCompanyNature());
				map.put("salary_month", u.getSalaryMonth());
				map.put("salary_internship_month", u.getSalaryInternshipMonth());
				map.put("salary_year", u.getSalaryYear());
				map.put("post", u.getPost());
				map.put("dimission_company", u.getDimissionCompany());
				map.put("dimission_time", u.getDimissionTime());
				map.put("dimission_reason", u.getDimissionReason());
				map.put("comment", u.getComment());
				map.put("employment_clazz_name",u.getEmploymentClazzName());
				map.put("srms_clazz_name",u.getSrmsClazzName());
				map.put("serial_number",u.getSerialNumber());
				map.put("flexible_information_1",u.getFlexibleInformation1());
				map.put("flexible_information_2",u.getFlexibleInformation2());
				map.put("school_data_search",u.getSchoolDataSearch());
			}
			// 学生基本信息
			map.put("realname", u.getName());
			dataList.add(map);
		}
		// 2.4 导出文件名
		String excelName = "student_list";
		// 3. 调用工具方法导出Excel
		ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

	}

	@ApiOperation(value = "导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "application/octet-stream")
	@GetMapping("download")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "realname", value = "姓名", paramType = "query"),
		@ApiImplicitParam(name = "clazzId", value = "杰普班级编号", paramType = "query"),
		@ApiImplicitParam(name = "status", value = "状态", paramType = "query"),
		@ApiImplicitParam(name = "channelIds", value = "渠道", paramType = "query"),
		@ApiImplicitParam(name = "stuTypes", value = "学生类型", paramType = "query"),
		@ApiImplicitParam(name = "year", value = "毕业年份", paramType = "query"),
		@ApiImplicitParam(name = "employmentTeacher", value = "就业部老师姓名", paramType = "query"),

	})
	public void download(HttpServletResponse response, @NotNull int page, int pageSize,String realname,Long clazzId,String status,Long[] channelIds,String[] stuTypes,String year,
						 String employmentTeacher,String employmentClazzName) throws Exception {
		// 2. 将excel导出
		// 2.1 excel头部数据
		String[] headList = new String[] {
				"身份证号","就业档案排序号","就业部老师","考研是否录取","报考院校及专业","灵活信息1","灵活信息2","就业部离校审批情况","模面成绩","面试评价","首轮就业意向调研","就业推荐回访记录","三方协议回访情况","学校系统匹配数据查找","三方协议签约情况","就业状态",
				"目前所在地","入职时间","首份工作公司","公司性质","转正年薪","实习月薪","转正月薪","工作岗位","离职公司","离职时间","离职理由","学员情况标注",
				"就业管理班号","系统班级号","校内班级","学号","姓名" ,
                "钉钉手机号","性别","出生日期","家庭地址","大学毕业时间","学历","学校","学院","专业","外语能力","本人手机号","本人qq","监护人手机号"
		};
		// 2.2 属性
		String[] fieldList = new String[] {
				"id_card","serial_number","employment_teacher","is_graduate","graduate_college","flexible_information_1","flexible_information_2","leave_check","interview_level","interview_comment","intention","recommend_record","tripartite_agreement","school_data_search","tripartite_agreement_status","status",
				"current_location","entry_time","company_name","company_nature","salary_year","salary_internship_month","salary_month","post","dimission_company","dimission_time","dimission_reason","comment",
				"employment_clazz_name", "srms_clazz_name", "clazz", "stu_num", "realname",
                "ddTel","gender","birth","homeAddress","graduationTime","education","school","college","major","flp","tel","qq","guardianTel"
		};

		// 2.3 数据列，需要转化
		List<Map<String, Object>> dataList = new ArrayList<>();
		PageVM<StudentEmploymentExtend> pageVM = studentEmploymentService.pageQuery(page, pageSize,realname,clazzId,status,channelIds,stuTypes,year,employmentTeacher,employmentClazzName);
		for (StudentEmploymentExtend u : pageVM.getList()) {
			Map<String, Object> map = new HashMap<>();
			// 就业信息
			StudentEmployment employment = u.getEmployment();
            // 日期处理函数
            SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
			if(employment != null) {
				map.put("id_card",employment.getIdCard());
				map.put("employment_teacher", employment.getEmploymentTeacher());
				map.put("is_graduate", employment.getIsGraduate());
				map.put("graduate_college", employment.getGraduateCollege());
				map.put("interview_level", employment.getInterviewLevel());
				map.put("interview_comment", employment.getInterviewComment());
				map.put("intention", employment.getIntention());
				map.put("leave_check", employment.getLeaveCheck());
				map.put("recommend_record", employment.getRecommendRecord());
				map.put("tripartite_agreement", employment.getTripartiteAgreement());
				map.put("tripartite_agreement_status", employment.getTripartiteAgreementStatus());
				map.put("status", employment.getStatus());
				map.put("current_location",employment.getCurrentLocation());
				map.put("entry_time", employment.getEntryTime());
				map.put("company_name", employment.getCompanyName());
				map.put("company_nature", employment.getCompanyNature());
				map.put("salary_month", employment.getSalaryMonth());
				map.put("salary_internship_month", employment.getSalaryInternshipMonth());
				map.put("salary_year", employment.getSalaryYear());
				map.put("post", employment.getPost());
				map.put("dimission_company", employment.getDimissionCompany());
				map.put("dimission_time", employment.getDimissionTime());
				map.put("dimission_reason", employment.getDimissionReason());
				map.put("comment", employment.getComment());
				map.put("employment_clazz_name",employment.getEmploymentClazzName());
				map.put("srms_clazz_name",employment.getSrmsClazzName());
				map.put("serial_number",employment.getSerialNumber());
				map.put("flexible_information_1",employment.getFlexibleInformation1());
				map.put("flexible_information_2",employment.getFlexibleInformation2());
				map.put("school_data_search",employment.getSchoolDataSearch());
			}
			// 学生基本信息
			map.put("clazz", u.getSchoolStuClazz());
			map.put("stu_num", u.getSchoolStuNo());
			map.put("realname", u.getRealname());

            map.put("ddTel", u.getDdTel());
            map.put("gender", u.getGender());
            // 出生日期
            String birth = "";
            try {
                birth = formatter.format(u.getBirth());
            } catch(Exception e) {
                birth = u.getBirth()+"";
            }
            map.put("birth", birth);
            map.put("homeAddress", u.getHomeAddress());
            // 毕业时间
            String  graduationTime ="";
            try	{
                graduationTime = formatter.format(u.getGraduationTime());
            } catch (Exception e){
                graduationTime = u.getGraduationTime()+"";
            }
            map.put("graduationTime",graduationTime);
            // 毕业院校
            if(u.getChannel()!=null) {
                // 学院
                map.put("college", u.getChannel().getName());
                if(u.getChannel().getParent()!=null) {
                    // 学校
                    map.put("school", u.getChannel().getParent().getName());
                }
            }
            map.put("education", u.getEducation());
            // 毕业院校
            if(u.getChannel()!=null) {
                // 学院
                map.put("college", u.getChannel().getName());
                if(u.getChannel().getParent()!=null) {
                    // 学校
                    map.put("school", u.getChannel().getParent().getName());
                }
            }
            map.put("major", u.getMajor());
            map.put("flp", u.getFlp());
            map.put("tel", u.getTel());
            map.put("qq", u.getQq());
            map.put("guardianTel",u.getGuardianTel());

			dataList.add(map);
		}
		// 2.4 导出文件名
		String excelName = "student_list";
		// 3. 调用工具方法导出Excel
		ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

	}

	public void inputStreamToFile(java.io.InputStream ins, File file) {
		try {
			java.io.OutputStream os = new java.io.FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
